<?php

namespace App\Service;

use App\Constants\RedisKey;
use App\Model\QmGameList;
use Hyperf\Redis\Redis;
use Hyperf\Utils\ApplicationContext;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;

class QmGameService {

    public static function getGameInfo($param): array {
        try {
            $redis = ApplicationContext::getContainer()->get(Redis::class);
        } catch (NotFoundExceptionInterface|ContainerExceptionInterface) {
            return [];
        }
        $gameInfo = $redis->get(RedisKey::GM_INFO . ':' . $param);
        if (empty($gameInfo)) {
            if (is_numeric($param)) {
                $gameInfo = QmGameList::query()->find($param);
            } else {
                $gameInfo = QmGameList::query()->where('hash', $param)->first();
            }
            if (!empty($gameInfo)) {
                $gameInfo = $gameInfo->toArray();
                $redis->set(RedisKey::GM_INFO . ':' . $param, json_encode($gameInfo), 3600);
            } else {
                return [];
            }
        } else {
            $gameInfo = json_decode($gameInfo, true);
        }

        return $gameInfo;
    }

    /**
     * 根据用户信息计算出当前角色在全服的唯一标识
     * @param $userInfo
     * @return string
     */
    public static function getRoleUnique($userInfo): string {
        return md5($userInfo['openid'] . $userInfo['id'] . $userInfo['last_role_id'] . $userInfo['game_hash']);
    }
}